'use strict';

const Controller = require('egg').Controller;

const sequelize = require('sequelize').Sequelize;
const Op = sequelize.Op;

class LendController extends Controller {
  constructor(ctx) {
    super(ctx);
  }

  async list() {
    const { ctx } = this;
    const pageNo = Number(ctx.query.pageNo || 1);
    const pageSize = Number(ctx.query.pageSize || 20);
    let user = ctx.state.user;
    let filter = ctx.query;
    if (user.role === 'customer') {
      filter.userId = user.id;
    }

    const result = await ctx.service.lend.list(pageNo, pageSize,filter);
    ctx.body = result
  }

  async add() {
    const { ctx, config } = this;
    let request = ctx.request.body;
    let user = ctx.state.user;
    if (user.role === 'customer') {
      ctx.throw(403, "用户权限不足！");
    }

    const result = await ctx.service.lend.add(request);
    ctx.body = result
  }

  async update() {
    const { ctx, config } = this;
    let request = ctx.request.body;
    const result = await ctx.service.lend.update(request);
    ctx.body = result
  }
  
  async calculate(){
    const { ctx, config } = this;
    const result = await ctx.service.lend.calculate();
    ctx.body = result
  }

  async return(){
    const { ctx, config } = this;
    let user = ctx.state.user;
    if (user.role === 'customer') {
      ctx.throw(403, "用户权限不足！");
    }

    let request = ctx.request.body;
    const result = await ctx.service.lend.return(request);
    ctx.body = result
  }

}

module.exports = LendController;

